package com.zishi.venuesbooking.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.zishi.venuesbooking.R;
import com.zishi.venuesbooking.entity.Friend;
import com.zishi.venuesbooking.entity.Reserve;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import de.hdodenhof.circleimageview.CircleImageView;

public class FriendAdapter extends RecyclerView.Adapter<FriendAdapter.FriendViewHolder> {

    private List<Friend> friends;

    public FriendAdapter(List<Friend> friends) {
        this.friends = friends;
    }

    @Override
    public FriendViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_my_friend, parent, false);
        return new FriendViewHolder(view);
    }

    @Override
    public void onBindViewHolder(FriendViewHolder holder, int position) {
        Friend friend = friends.get(position);
        holder.bind(friend);
    }

    @Override
    public int getItemCount() {
        return friends.size();
    }

    // 更新数据
    public void updateData(List<Friend> newFriends) {
        friends.clear();
        friends.addAll(newFriends);
        notifyDataSetChanged();
    }

    // 添加新评论
    public void addFriend(Friend friend) {
        friends.add(0, friend); // 添加到列表顶部
        notifyItemInserted(0);
    }

    static class FriendViewHolder extends RecyclerView.ViewHolder {
        private final CircleImageView civAvatar = itemView.findViewById(R.id.civ_friend_avatar);
        private final TextView tvFriendName = itemView.findViewById(R.id.tv_friend_name);
        private final TextView tvFriendLastMessage = itemView.findViewById(R.id.tv_friend_last_message);
        private final TextView tvFriendLastMessageTime = itemView.findViewById(R.id.tv_friend_last_message_time);

        public FriendViewHolder(@NonNull View itemView) {
            super(itemView);
        }

        public void bind(Friend friend) {
            // 加载用户头像
            Glide.with(itemView.getContext())
                    .load(friend.getFriendAvatar())
                    .placeholder(R.drawable.avata_1)
                    .into(civAvatar);

            tvFriendName.setText(friend.getFriendName());
            tvFriendLastMessage.setText(friend.getFriendLastMessage());
            tvFriendLastMessageTime.setText(friend.getFriendLastMessageTime());
        }

        private String formatTime(long time) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
            return sdf.format(new Date(time));
        }
    }
}
